package com.clp.protocol.iec104.apdu.asdu.infoobj.infoelem.filetransfer;

import com.clp.protocol.iec104.definition.ConstVal;
import com.clp.protocol.iec104.definition.Ft;
import com.clp.protocol.core.utils.ByteUtil;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * 读文件数据传输确认 附加数据包
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class FileRDataConAttachPack extends AttachPack {
    @Override
    public Ft.OperationTag operationTag() {
        return Ft.OperationTag.FILE_RDATA_CON;
    }

    /**
     * 文件id
     */
    private long fileId;
    /**
     * 数据段号
     */
    private long dataSegment;
    /**
     * 结果描述字
     */
    private Ft.FileRDataConRD fileRDataConRD;

    @Override
    public FileRDataConAttachPack refreshFrom(ByteBuf buf) {
        checkOperationTag(buf.readByte());
        // 文件id
        byte[] fileIdBytes = new byte[ConstVal.FILE_ID_LEN]; buf.readBytes(fileIdBytes);
        this.fileId = ByteUtil.bytes4ToLongLE(fileIdBytes);
        // 数据段号
        byte[] dataSegmentBytes = new byte[ConstVal.DATA_SEGMENT_LEN]; buf.readBytes(dataSegmentBytes);
        this.dataSegment = ByteUtil.bytes4ToLongLE(dataSegmentBytes);
        // 结果描述字
        this.fileRDataConRD = Ft.FileRDataConRD.gain(buf.readByte());
        return this;
    }

    @Override
    public boolean isValid() {
        if (fileId < 0 || fileId > 0xFFFFFFFFL) return false;
        if (dataSegment < 0 || dataSegment > 0xFFFFFFFFL) return false;
        return fileRDataConRD != null;
    }

    @Override
    public void writeBytesTo(ByteBuf buf) {
        // 填写操作标识
        buf.writeByte(operationTag().getVal());
        // 文件id
        buf.writeBytes(ByteUtil.longToBytes4LE(fileId));
        // 数据段号
        buf.writeBytes(ByteUtil.longToBytes4LE(dataSegment));
        // 结果描述字
        buf.writeByte(fileRDataConRD.getVal());
    }

    @Override
    public String toString() {
        return "文件id：" + fileId + ", 数据段号：" + dataSegment + ", 结果描述字：" + fileRDataConRD;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FileRDataConAttachPack that = (FileRDataConAttachPack) o;
        return fileId == that.fileId && dataSegment == that.dataSegment && fileRDataConRD == that.fileRDataConRD;
    }

    @Override
    public int hashCode() {
        return Objects.hash(fileId, dataSegment, fileRDataConRD);
    }
}
